package com.etop.ondoc.dao;

import com.etop.ondoc.util.Pager;
import com.etop.ondoc.beans.User;
import com.etop.ondoc.util.HibernateUtil;
import java.util.List;
import org.hibernate.Session;

/**
 *
 * @author jansing lz_jansing@163.com
 */
public class UserDao {

    public void add(User user) {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            throw e;
        } finally {
            HibernateUtil.close(session);
        }
    }

    public void delete(User user) {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            session.beginTransaction();
            session.delete(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            throw e;
        } finally {
            HibernateUtil.close(session);
        }
    }

    public void update(User user) {
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            session.beginTransaction();
            session.update(user);
            session.getTransaction().commit();
        } catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            throw e;
        } finally {
            HibernateUtil.close(session);
        }
    }

    public User load(int id) {
        Session session = HibernateUtil.openSession();
        User user = (User) session.get(User.class, id);
        HibernateUtil.close(session);
        return user;
    }

    public User loadByUsername(String username) {
        Session session = HibernateUtil.openSession();
        User user = (User) session.createQuery("from User where username=:username")
                .setString("username", username)
                .uniqueResult();
        HibernateUtil.close(session);
        return user;
    }

    public List<User> list() {
        Session session = HibernateUtil.openSession();
        List<User> list = session.createQuery("from User").list();
        HibernateUtil.close(session);
        return list;
    }
}
